import {defineComponent, PropType, ref, h, onMounted} from "vue";
import CdlForm from "@/components/form"
import {FormTree} from "@/interfaces/components/Form";
import {Bills, BillType} from "@/interfaces/views/finance/bills";
import {FormData} from "@/interfaces/components/Page";
import {useGetBillTypeSelectApi} from "@/api/finance/finance";
import {useShipperListApi} from "@/api/vehicle/shipper";
import {useGetDriverListApi} from "@/api/vehicle/driver";
import {useGetVehicleListApi} from "@/api/vehicle/vehicle";
import constant from "@/utils/constant";
import {userStore} from "@/store/modules/user";
import {cloneDeep} from "lodash";

export default defineComponent({
    name: "CdlBill",
    props: {
        types: {
            type: Object as PropType<number[]>,
            required: false
        },
        init: {
            type: String as PropType<"预付款" | "尾款" | "运费">
        }
    },
    setup(props, {expose}) {
        const store = userStore()
        const formTree: FormTree<Bills> = [
            [
                {label: "账单名称", component: "select", prop: "billTypeId", serviceOptionKey: "billTypeList",
                    optionProps: {label: "name", value: "id"}, placeholder: "请选择账单名称",
                    changeMethod: (val, data, enable, changeCallBack) => {
                        if(!val) return
                        enable["form-item-billType"] = !!val
                        enable["form-item-modeId"] = !!val
                        const bill = billTypes.find(item => item.id === val)!
                        data.billType = bill.type
                        data.modeId = bill.mode
                        enable["form-item-gatherName"] = bill.mode === 1
                        enable["form-item-paypalName"] = bill.mode === 2
                        enable["form-item-gatherId"] = [3,5].includes(bill.mode) && (changeCallBack.gatherIdCreate(data) || true)
                        enable["form-item-paypalId"] = [4,6].includes(bill.mode) && (changeCallBack.paypalIdCreate(data) || true)
                        enable["form-item-carId"] = ![5,6].includes(bill.mode) && (changeCallBack.carIdCreate(data) || true)
                    }, rule: {required: true, message: "必须选择账单名称", trigger: "change"}}
            ],
            [
                {label: "账单类型", prop: "billType", component: "tag", dict: "bill_type", enable: false},
                {label: "收入支出", prop: "modeId", component: "tag", dict: "bill_mode", enable: false},
            ],
            [
                {label: "收款人名称", component: "select", prop: "gatherId", serviceOptionKey: "personList",
                    create: getPersonList, optionProps: {label: "name", value: "id"}, filterable: true, enable: false,
                    placeholder: "请选择收款人名字", rule: {required: true, message: "必须选择收款人名称", trigger: "change"}},
                {label: "收款人名称", component: "input", prop: "gatherName", enable: false,
                    rule: {required: true, message: "必须填写收款人名称", trigger: "blur"}},
                {label: "付款人名称", component: "select", prop: "paypalId", serviceOptionKey: "personList",
                    create: getPersonList, optionProps: {label: "name", value: "id"}, filterable: true, enable: false,
                    placeholder: "请选择付款人名字", rule: {required: true, message: "必须选择付款人名称", trigger: "change"}},
                {label: "付款人名称", component: "input", prop: "paypalName", enable: false,
                    rule: {required: true, message: "必须填写收款人名称", trigger: "blur"}},
                {label: "关联车辆", component: "select", prop: "carId", serviceOptionKey: "vehicleList",
                    create: getVehicleList, optionProps: {label: "licensePlate", value: "id"}, enable: false,
                    placeholder: "请选择车辆"}
            ],
            [
                {label: "金额", component: "input", prop: "amount", type: "number"}
            ],
            [
                {label: "交易单号", component: "input", prop: "transNo"},
                {label: "账单说明", component: "input", prop: "billRemark"}
            ],
            [
                {label: "附加图片", component: "uploads", prop: "imageArr", action: constant.uploadUrl}
            ],
            [
                {label: "备注", component: "input", prop: "remark", type: "textarea"}
            ]
        ]
        const form = ref<FormData<Bills>>({
            billTypeName: undefined,
            billTypeId: undefined,
            billId: undefined,
            billType: undefined,
            modeId: undefined,
            gatherId: undefined,
            gatherName: undefined,
            paypalId: undefined,
            paypalName: undefined,
            carId: undefined,
            carNo: undefined,
            amount: undefined,
            transNo: "",
            billRemark: "",
            imageArr: [],
            remark: ""
        })
        const formRef = ref()
        const initConfig: {[key: string]: any} = {"billTypeList": getBillTypeList}
        let billTypes: BillType[] = []
        if(props.init) init()

        /**
         * 初始化数据
         */
        function init(){
            formTree[0][0].disabled = true
            formTree[1][0].enable = true
            formTree[1][1].enable = true
            switch (props.init){
                case "预付款":
                    form.value.billTypeId = "1"
                    formTree[2][2].enable = true
                    form.value.billType = 2
                    form.value.modeId = 6
                    initConfig["personList"] = getShipperList
                    break
                case "尾款":
                    form.value.billTypeId = "3"
                    formTree[2][2].enable = true
                    form.value.billType = 2
                    form.value.modeId = 6
                    initConfig["personList"] = getShipperList
                    break
            }
        }
        /**
         * 提交数据
         */
        function parentSubmit(){
            return new Promise((resolve, reject) => {
                formRef.value.parentSubmit().then((res: any) =>{
                    res.billTypeName = billTypes.find(item => item.id === res.billTypeId)?.name
                    if(res.modeId % 2 === 0) {
                        const person = personList.find(item => item.id === res.paypalId)
                        res.paypalName = person.contact? person.contact : person.name
                        res.gatherId = store.user.id
                        res.gatherName = store.user.username
                    }
                    else {
                        const person = personList.find(item => item.id === res.gatherId)
                        res.gatherName = person.contact? person.contact : person.name
                        res.paypalId = store.user.id
                        res.paypalName = store.user.username
                    }
                    if(res.carId) res.carNo = vehicleList.find(item => item.id === res.carId).licensePlate
                    resolve(cloneDeep(res))
                })
            })

        }
        /**
         * 获取账单名称
         */
        function getBillTypeList(){
            return new Promise((resolve, reject) => {
                useGetBillTypeSelectApi({
                    types: props.types
                }).then(res =>{
                    // res.data.forEach((item: any) => item.id = parseInt(item.id))
                    billTypes = res.data
                    resolve(res.data)
                })
            })
        }
        let personList: any[] = []
        /**
         * 获取人员列表
         * @param serviceOptions
         * @param data
         */
        function getPersonList(serviceOptions: any, data: Bills){
            if([5,6].includes(data.modeId)){
                useShipperListApi().then(res => {
                    serviceOptions.personList = res.data.map((item: any) => {
                        return {
                            id: item.id,
                            name: item.contact
                        }
                    })
                    personList = serviceOptions.personList
                })
            }else if([[3,4].includes(data.modeId)]){
                useGetDriverListApi().then(res => {
                    serviceOptions.personList = res.data
                    personList = res.data
                })
            }
        }

        /**
         * 获取托运人列表
         */
        function getShipperList(){
            return new Promise((resolve, reject) => {
                useShipperListApi().then(res => {
                    personList = res.data.map((item: any) => {
                        return {
                            id: item.id,
                            name: item.contact
                        }
                    })
                    resolve(personList)
                })
            })
        }

        let vehicleList: any[] = []

        /**
         * 获取车辆列表
         * @param serviceOptions
         */
        function getVehicleList(serviceOptions: any){
            useGetVehicleListApi().then(res => {
                vehicleList = res.data
                serviceOptions.vehicleList = res.data
            })
        }
        expose({
            parentSubmit
        })

        return () =>(<CdlForm ref={formRef} templateTree={formTree} model={form.value}
                              init={initConfig}></CdlForm>)
    }
})

